<?php
/**
 * Created by PhpStorm.
 * @User: 王崇全
 * @Date: 2018/12/22 16:25
 */

namespace app\common\model;

use think\Db;

/**
 * 管理员层级-结构
 * @author  王崇全
 * @date    2018/12/22 16:25
 * @package app\common\model
 */
class AdminHierarchy extends Catalog
{

    const TAB_NAME        = "admin_hierarchy";
    const TAB_DETAIL_NAME = "admin_hierarchy_detail";

    public function __construct()
    {
        parent::__construct(self::TAB_NAME);
    }

    /**
     * 添加层级
     * @author 王崇全
     * @date   2018/12/22 16:50
     * @param string $title 层级名称
     * @param int    $pgid  父层级, 默认时,将要添加的层级为根层级
     * @return int   返回新增id
     * @throws \Exception
     */
    public function addHierarchy(string $title = '', int $pgid = 0)
    : int {

        Db::startTrans();
        try {
            $ahid = $this->add($title, $pgid);

            Db::name(self::TAB_DETAIL_NAME)
              ->insert([
                  "acid" => $ahid,
              ]);
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

        Db::commit();
        return $ahid;
    }

    /**
     * 层级信息
     * @author 王崇全
     * @date   2018/12/22 16:55
     * @param int $id 层级ID
     * @return array
     * @throws
     */
    public function hierarchyInfo(int $id)
    : array {

        //todo: 加入detail的字段
        $res = Db::name(self::TAB_NAME)
                 ->alias("ah")
                 ->field([
                     "ah.title",
                     "ah.pid",
                 ])
                 ->where("id", $id)
                 ->leftJoin(self::TAB_DETAIL_NAME." ahd")
                 ->find();

        return $res;
    }

    /**
     * 层级列表
     * @author 王崇全
     * @date   2018/12/22 18:00
     * @param int  $pid       父层级ID , 0为根层级
     * @param bool $onlyChild 是否只返回直接子层级
     * @return array
     * @throws
     */
    public function hierarchyList(int $pid = 0, bool $onlyChild = false)
    : array {
        $pInfo = Db::name(self::TAB_NAME)
                   ->field([
                       "ln",
                       "rn",
                   ])
                   ->where("id", $pid)
                   ->find();
        if (!$pInfo) {
            throw new \Exception("父层级不存在");
        }

        //todo: 加入detail的字段
        $db = Db::name(self::TAB_NAME)
                ->alias("ah")
                ->field([
                    "ah.id",
                    "ah.title",
                    "ah.pid",
                ])
                ->where("ah.ln", ">", $pInfo["ln"])
                ->where("ah.rn", "<", $pInfo["rn"]);
        if ($onlyChild) {
            $db->where("ah.pid", $pid);
        }

        $list = $db->leftJoin(self::TAB_DETAIL_NAME." ahd","ah.id = ahd.id")
                   ->select();
        if (!$list) {
            return [];
        }

        //整理成树型
        if (!$onlyChild) {
            $list = $this->generateTree($list);
        }

        return $list;
    }

    /**
     * 删除层级
     * @author 王崇全
     * @date   2018/12/22 18:11
     * @param int $id 层级ID
     * @return void
     * @throws \Exception
     */
    public function delHierarchy(int $id)
    : void {

        Db::startTrans();
        try {

            $this->del($id);

            Db::name(self::TAB_DETAIL_NAME)
              ->where("acid", $id)
              ->delete();

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception("层级删除失败");
        }
        Db::commit();
    }

    /**
     * exitHierarchy
     * @author 王崇全
     * @date   2018/12/23 13:34
     * @param int   $id
     * @param array $data ["title"=>层级名称,"pid"=>父层级ID,]
     * @return void
     * @throws
     */
    public function exitHierarchy(int $id, array $data)
    : void {

        $mapKey = array_keys($data);

        $mapKeyHierarchy = array_intersect($mapKey, [
            "title",
            "pid",
        ]);
        if (!empty($mapKeyHierarchy)) { //修改 层级结构部分

            $this->edit($id, $data["title"] ?? null, $data["pid"] ?? null);
        }

        $mapKeyHierarchyDetail = array_intersect($mapKey, [//todo: 加入detail的字段
        ]);
        if (!empty($mapKeyHierarchyDetail)) { //修改 层级内容部分


        }

    }

    /**
     * 获取下级编号
     * @author 王海东
     * @date
     * @param int $pgid 层级id
     * @return array
     */
    public function getIds(int $pgid)
    {
        $data = $this->getIdsByPgid($pgid);
        return $data;
    }
}